<?php
/**
 * Created by PhpStorm.
 * User: 李大爷
 * Date: 2019/3/5
 * Time: 16:05
 */

namespace app\controllers;

use app\models\Node;
use app\models\RemarkForm;
use app\models\User;
use Yii;
use app\models\Project;
use yii\db\Query;
use yii\helpers\ArrayHelper;
use yii\helpers\Url;
use yii\helpers\VarDumper;
use yii\web\NotFoundHttpException;
use yii\web\UploadedFile;

class ProjectController extends BaseController
{
    /**
     * 项目管理列表
     * @return string|\yii\web\Response
     */
    public function actionIndex()
    {
        if (Yii::$app->request->isAjax){
            //筛选条件
            $where = ['and'];
            $name = Yii::$app->request->get('name');
            if ($name){
                $where[] = ['=','name',$name];
            }
            $phone = Yii::$app->request->get('phone');
            if ($phone){
                $where[] = ['or',['=','phone',$phone],['=','other_phone',$phone]];
            }
            $node_id = Yii::$app->request->get('node_id');
            if ($node_id){
                $where[] = ['=','node_id',$node_id];
            }
            $created_user_id = Yii::$app->request->get('created_user_id');
            if ($created_user_id){
                $where[] = ['=','created_user_id',$created_user_id];
            }
            $follow_at_start = Yii::$app->request->get('follow_at_start');
            $follow_at_end = Yii::$app->request->get('follow_at_end');
            if ($follow_at_start && !$follow_at_end){
                $where[] = ['>=','follow_at',strtotime($follow_at_start)];
            }elseif (!$follow_at_start && $follow_at_end){
                $where[] = ['<=','follow_at',strtotime($follow_at_end)];
            }elseif ($follow_at_start && $follow_at_end){
                $where[] = ['between','follow_at',strtotime($follow_at_start),strtotime($follow_at_end)];
            }
            $next_follow_at_start = Yii::$app->request->get('next_follow_at_start');
            $next_follow_at_end = Yii::$app->request->get('next_follow_at_end');
            if ($next_follow_at_start && !$next_follow_at_end){
                $where[] = ['>=','next_follow_at',strtotime($next_follow_at_start)];
            }elseif (!$next_follow_at_start && $next_follow_at_end){
                $where[] = ['<=','next_follow_at',strtotime($next_follow_at_end)];
            }elseif ($next_follow_at_start && $next_follow_at_end){
                $where[] = ['between','next_follow_at',strtotime($next_follow_at_start),strtotime($next_follow_at_end)];
            }
            $created_at_start = Yii::$app->request->get('created_at_start');
            $created_at_end = Yii::$app->request->get('created_at_end');
            if ($created_at_start && !$created_at_end){
                $where[] = ['>=','created_at',strtotime($created_at_start)];
            }elseif (!$created_at_start && $created_at_end){
                $where[] = ['<=','created_at',strtotime($created_at_end)];
            }elseif ($created_at_start && $created_at_end){
                $where[] = ['between','created_at',strtotime($created_at_start),strtotime($created_at_end)];
            }

            $where[] = ['and',['=','deleted_at',0],['=','deleted_user_id',0]];
            //是否有权限查看所有记录
            if (!Yii::$app->user->can('project.display_all')){
                $where[] = ['and',['or',['=','created_user_id',Yii::$app->user->identity->id],['=','created_user_id',0]]];
            }
            $query = Project::find()->with(['node','user'])->where($where)->orderBy('id desc');
            $count = $query->count();

            $page = Yii::$app->request->get('page',1);
            $limit = Yii::$app->request->get('limit',10);
            $data = $query->offset(($page-1)*$limit)->limit($limit)->asArray()->all();
            foreach ($data as &$d){
                $d['show_url'] = Url::to(['show','id'=>$d['id']]);
                $d['edit_url'] = Url::to(['edit','id'=>$d['id']]);
                $d['node_url'] = Url::to(['node','id'=>$d['id']]);
                $d['remark_url'] = Url::to(['remark','id'=>$d['id']]);
                $d['destroy_url'] = Url::to(['destroy','id'=>$d['id']]);
                $d['sex_text'] = Project::$sex_info[$d['sex']];
                $d['follow_at'] = $d['follow_at']?date('Y-m-d H:i',$d['follow_at']):'-';
                $d['next_follow_at'] = $d['next_follow_at']?date('Y-m-d H:i',$d['next_follow_at']):'-';
                $d['created_at'] = $d['created_at']?date('Y-m-d H:i',$d['created_at']):'-';
                $d['node_name'] = $d['node']['name'];
                $d['created_user_name'] = $d['user']['username'];
            }
            return $this->asJson([
                'code' => 0,
                'msg' => '请求成功',
                'count' => $count,
                'data' => $data
            ]);
        }
        $nodes = Node::find()->orderBy('sort asc')->addOrderBy('id asc')->asArray()->all();
        $users = User::find()->all();
        return $this->render('index',['nodes'=>$nodes,'users'=>$users]);
    }

    /**
     * 添加项目
     * @return string|\yii\web\Response
     */
    public function actionCreate()
    {
        $model = new Project();
        if (Yii::$app->request->isPost){
            $data = Yii::$app->request->post();
            $model->scenario = 'create';
            if ($model->load($data,'')&&$model->save()){
                Yii::$app->session->setFlash('info','添加成功');
                return $this->redirect(['index']);
            }
        }
        return $this->render('create',['model'=>$model]);
    }

    /**
     * 编辑项目
     * @param $id
     * @return string|\yii\web\Response
     */
    public function actionEdit($id)
    {
        $model = Project::findOne($id);
        if ($model===null){
            throw new NotFoundHttpException('项目不存在');
        }

        if (Yii::$app->request->isPost){
            $data = Yii::$app->request->post();
            $model->scenario = 'edit';
            if ($model->load($data,'')&&$model->save()){
                Yii::$app->session->setFlash('info','更新成功');
                return $this->redirect(['index']);
            }
        }
        return $this->render('edit',['model'=>$model]);
    }

    /**
     * 项目详情
     * @param $id
     * @return string
     * @throws NotFoundHttpException
     */
    public function actionShow($id)
    {
        $model = Project::find()->with('node')->where(['id'=>$id])->one();
        if ($model===null){
            throw new NotFoundHttpException('项目不存在');
        }
        $follow = (new Query())->from('project_remark as r')
            ->leftJoin('user as u','r.user_id=u.id')
            ->select(['u.username','r.content','r.created_at as follow_at','r.next_follow_at'])
            ->where(['r.project_id'=>$id])
            ->orderBy('r.id desc')
            ->one();
        return $this->render('show',['model'=>$model,'follow'=>$follow]);
    }

    /**
     * 项目备注
     * @param $id
     * @return string|\yii\web\Response
     * @throws NotFoundHttpException
     */
    public function actionRemark($id)
    {
        $model = Project::findOne($id);
        if ($model===null){
            throw new NotFoundHttpException('项目不存在');
        }
        $form = new RemarkForm();
        if (Yii::$app->request->isPost){
            $data = Yii::$app->request->post();
            if ($form->load($data,'')&&$form->save()){
                Yii::$app->session->setFlash('info','添加备注成功');
                return $this->redirect(['show','id'=>$id]);
            }
        }
        return $this->render('remark',['model'=>$model,'form'=>$form]);
    }

    /**
     * 项目节点更新
     * @param $id
     * @return string|\yii\web\Response
     * @throws NotFoundHttpException
     */
    public function actionNode($id)
    {
        $model = Project::findOne($id);
        if ($model===null){
            throw new NotFoundHttpException('项目不存在');
        }
        if (Yii::$app->request->isPost){
            $data = Yii::$app->request->post();
            $model->scenario = 'node';
            if ($model->load($data,'')&&$model->updateNode()){
                Yii::$app->session->setFlash('info','更新节点成功');
                return $this->redirect(['show','id'=>$id]);
            }
        }
        $nodes = Node::find()->orderBy('sort asc')->addOrderBy('id asc')->asArray()->all();
        return $this->render('node',['model'=>$model,'nodes'=>$nodes]);
    }

    /**
     * 删除项目
     * @param $id
     * @return \yii\web\Response
     * @throws \Throwable
     * @throws \yii\db\StaleObjectException
     */
    public function actionDestroy($id)
    {
        $model = Project::findOne($id);
        if ($model===null){
            return $this->asJson(['code'=>1,'msg'=>'项目不存在']);
        }
        if ($model->softDelete()){
            return $this->asJson(['code'=>0,'msg'=>'删除成功']);
        }
        return $this->asJson(['code'=>0,'msg'=>'删除失败']);
    }

    /**
     * 项目节点进度
     * @param $id
     * @return \yii\web\Response
     */
    public function actionNodeList($id)
    {
        if (Yii::$app->request->isAjax){
            $query = (new Query())->from('project_node as n')
            ->leftJoin('user as u','n.user_id=u.id')
            ->select(['n.old','n.new','n.content','n.created_at','u.username'])
            ->where(['n.project_id'=>$id])
            ->orderBy('n.id desc');
            $count = $query->count();
            $page = Yii::$app->request->get('page',1);
            $limit = Yii::$app->request->get('limit',10);
            $data = $query->offset(($page-1)*$limit)->limit($limit)->all();
            $nodes = Node::find()->select(['name','id'])->indexBy('id')->column();
            foreach ($data as &$d){
                $d['created_at'] = $d['created_at']?date('Y-m-d H:i',$d['created_at']):'-';
                $d['old'] = ArrayHelper::getValue($nodes,$d['old']);
                $d['new'] = ArrayHelper::getValue($nodes,$d['new']);
            }
            return $this->asJson([
                'code' => 0,
                'msg' => '请求成功',
                'count' => $count,
                'data' => $data
            ]);
        }
    }

    /**
     * 项目备注进度
     * @param $id
     * @return \yii\web\Response
     */
    public function actionRemarkList($id)
    {
        if (Yii::$app->request->isAjax){
            $query = (new Query())->from('project_remark as r')
                ->leftJoin('user as u','r.user_id=u.id')
                ->select(['r.content','r.next_follow_at','r.created_at','u.username'])
                ->where(['r.project_id'=>$id])
                ->orderBy('r.id desc');
            $count = $query->count();
            $page = Yii::$app->request->get('page',1);
            $limit = Yii::$app->request->get('limit',10);
            $data = $query->offset(($page-1)*$limit)->limit($limit)->all();
            foreach ($data as &$d){
                $d['created_at'] = $d['created_at']?date('Y-m-d H:i',$d['created_at']):'-';
                $d['next_follow_at'] = $d['next_follow_at']?date('Y-m-d H:i',$d['next_follow_at']):'-';
            }
            return $this->asJson([
                'code' => 0,
                'msg' => '请求成功',
                'count' => $count,
                'data' => $data
            ]);
        }
    }

    /**
     * 项目概要
     * @return string|\yii\web\Response
     */
    public function actionCount()
    {
        if (Yii::$app->request->isAjax){
            $data = [];
            $nodes = Node::find()->orderBy('sort asc')
                ->addOrderBy('id asc')
                ->with('project')
                ->all();
            foreach ($nodes as $node){
                $data[$node['name']] = count($node['project']);
            }
            return $this->asJson([
                'code' => 0,
                'msg' => '请求成功',
                'data' => $data,
            ]);
        }
        $day_start = mktime(0,0,0,date('m'),date('d'),date('Y'));
        $day_end = mktime(0,0,0,date('m'),date('d')+1,date('Y'));
        $projects = Project::find()->where(['and',['=','deleted_at',0],['=','deleted_user_id',0],['between','next_follow_at',$day_start,$day_end]])
            ->orderBy('next_follow_at asc')
            ->limit(9)
            ->all();
        foreach ($projects as &$p){
            $p['follow_at'] = $p['follow_at']?date('Y-m-d H:i',$p['follow_at']):'-';
        }
        return $this->render('count',['projects'=>$projects]);
    }

    public function actionDeleteList()
    {
        $users = User::find()->indexBy("id")->all();

        if (Yii::$app->request->isAjax){
            //筛选条件
            $where = ['and'];
            $name = Yii::$app->request->get('name');
            if ($name){
                $where[] = ['=','name',$name];
            }
            $phone = Yii::$app->request->get('phone');
            if ($phone){
                $where[] = ['or',['=','phone',$phone],['=','other_phone',$phone]];
            }

            $created_user_id = Yii::$app->request->get('created_user_id');
            if ($created_user_id){
                $where[] = ['=','created_user_id',$created_user_id];
            }
            $follow_user_id = Yii::$app->request->get('follow_user_id');
            if ($follow_user_id){
                $where[] = ['=','follow_user_id',$follow_user_id];
            }
            $deleted_user_id = Yii::$app->request->get('deleted_user_id');
            if ($deleted_user_id){
                $where[] = ['=','deleted_user_id',$deleted_user_id];
            }

            $created_at_start = Yii::$app->request->get('created_at_start');
            $created_at_end = Yii::$app->request->get('created_at_end');
            if ($created_at_start && !$created_at_end){
                $where[] = ['>=','created_at',strtotime($created_at_start)];
            }elseif (!$created_at_start && $created_at_end){
                $where[] = ['<=','created_at',strtotime($created_at_end)];
            }elseif ($created_at_start && $created_at_end){
                $where[] = ['between','created_at',strtotime($created_at_start),strtotime($created_at_end)];
            }
            $follow_at_start = Yii::$app->request->get('follow_at_start');
            $follow_at_end = Yii::$app->request->get('follow_at_end');
            if ($follow_at_start && !$follow_at_end){
                $where[] = ['>=','follow_at',strtotime($follow_at_start)];
            }elseif (!$follow_at_start && $follow_at_end){
                $where[] = ['<=','follow_at',strtotime($follow_at_end)];
            }elseif ($follow_at_start && $follow_at_end){
                $where[] = ['between','follow_at',strtotime($follow_at_start),strtotime($follow_at_end)];
            }
            $deleted_at_start = Yii::$app->request->get('deleted_at_start');
            $deleted_at_end = Yii::$app->request->get('deleted_at_end');
            if ($deleted_at_start && !$deleted_at_end){
                $where[] = ['>=','deleted_at',strtotime($deleted_at_start)];
            }elseif (!$deleted_at_start && $deleted_at_end){
                $where[] = ['<=','deleted_at',strtotime($deleted_at_end)];
            }elseif ($deleted_at_start && $deleted_at_end){
                $where[] = ['between','deleted_at',strtotime($deleted_at_start),strtotime($deleted_at_end)];
            }

            $where[] = ['and',['>','deleted_at',0],['>','deleted_user_id',0]];
            $query = Project::find()->where($where)->orderBy('id desc');
            $count = $query->count();

            $page = Yii::$app->request->get('page',1);
            $limit = Yii::$app->request->get('limit',10);
            $data = $query->offset(($page-1)*$limit)->limit($limit)->asArray()->all();
            foreach ($data as &$d){
                /*$d['show_url'] = Url::to(['show','id'=>$d['id']]);
                $d['edit_url'] = Url::to(['edit','id'=>$d['id']]);
                $d['node_url'] = Url::to(['node','id'=>$d['id']]);
                $d['remark_url'] = Url::to(['remark','id'=>$d['id']]);
                $d['destroy_url'] = Url::to(['destroy','id'=>$d['id']]);
                $d['sex_text'] = Project::$sex_info[$d['sex']];*/
                $d['return_url'] = Url::to(['delete-return','id'=>$d['id']]);
                $d['created_at'] = $d['created_at']?date('Y-m-d H:i',$d['created_at']):'-';
                $d['follow_at'] = $d['follow_at']?date('Y-m-d H:i',$d['follow_at']):'-';
                $d['deleted_at'] = $d['deleted_at']?date('Y-m-d H:i',$d['deleted_at']):'-';
                $d['created_user_name'] = isset($users[$d['created_user_id']])?$users[$d['created_user_id']]['username']:'-';
                $d['follow_user_name'] = isset($users[$d['follow_user_id']])?$users[$d['follow_user_id']]['username']:'-';
                $d['deleted_user_name'] = isset($users[$d['deleted_user_id']])?$users[$d['deleted_user_id']]['username']:'-';
            }
            return $this->asJson([
                'code' => 0,
                'msg' => '请求成功',
                'count' => $count,
                'data' => $data
            ]);
        }
        return $this->render('delete-list',['users'=>$users]);
    }

    public function actionDeleteReturn($id)
    {
        $project = Project::find()->where(['and',['>','deleted_at',0],['>','deleted_user_id',0],['=','id',$id]])->one();
        if ($project == null){
            return $this->asJson(['code'=>1,'msg'=>'记录不存在或已还原']);
        }
        $project->deleted_at = 0;
        $project->deleted_user_id = 0;
        if ($project->save(false)){
            return $this->asJson(['code'=>0,'msg'=>'还原成功']);
        }
        return $this->asJson(['code'=>1,'msg'=>'还原失败']);
    }

    public function actionCall()
    {
        return $this->render('call');
    }

    public function actionImport()
    {
        set_time_limit(0);
        $file = UploadedFile::getInstanceByName('file');
        $path = 'uploadfile/';
        $fileName = time().uniqid();
        $ext = $file->getExtension();
        if (!file_exists($path)) {
            mkdir($path, 0755, true);
        }
        $fullName = $path.$fileName.'.'.$ext;
        if($file->saveAs($fullName)) {
            //文件内容读取
            $data = [];
            try{
                if ($ext == 'xlsx'){
                    $reader = new \PHPExcel_Reader_Excel2007();
                }elseif ($ext == 'xls'){
                    $reader = new \PHPExcel_Reader_Excel5();
                }else{
                    return $this->asJson(['code'=>1,'msg'=>'上传文件格式不正确']);
                }
                $obj = $reader->load($fullName);
                $sheet = $obj->getSheet(0);
                $column_total = $sheet->getHighestColumn();//最大列，结果为A,B,C.....
                $row_total = $sheet->getHighestRow(); //最大行
                $cell_name = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');
                $column_total = array_search($column_total,$cell_name); //将最大行字母转为数字
                //row 从2开始表示忽略第一行标题
                for ($row=2; $row<=$row_total; $row++){
                    $item = [];
                    for ($column=0; $column<=$column_total; $column++){
                        $cell_val = $sheet->getCellByColumnAndRow($column,$row)->getValue();
                        if ($column==1){ //第二列为性别，将进行转换
                            $cell_val = ArrayHelper::getValue(['男'=>1,'女'=>2,'保密'=>3],$cell_val,3);
                        }
                        array_push($item,$cell_val);
                    }
                    if (!empty($item) && count($item) == 4) {
                        $item[] = time(); //对应created_at
                        $item[] = time(); //对应updated_at
                        $item[] = Yii::$app->user->identity->id; //对应created_user_id
                        array_push($data,$item);
                    }
                }
            }catch (\Exception $exception){
                return $this->asJson(['code'=>1,'msg'=>'读取文件内容错误','data'=>$exception->getMessage()]);
            }

            //写入数据库
            if (!empty($data)){
                $db = Yii::$app->db;
                //设置mysql的max_allowed_packet为500M = 1024*1024*500 防止sql过大mysql报错
                $db->createCommand("set global max_allowed_packet=524288000")->execute();
                $transaction = $db->beginTransaction();
                $column = ['name','sex','phone','company','created_at','updated_at','created_user_id'];
                $column_data = $data;
                try{
                    $db->createCommand()->batchInsert('project',$column,$column_data)->execute();
                    $transaction->commit();
                    //导入完成后删除上传的文件
                    unlink($fullName);
                    return $this->asJson(['code'=>0,'msg'=>'导入完成']);
                }catch (\Exception $exception){
                    $transaction->rollBack();
                    return $this->asJson(['code'=>1,'msg'=>'导入失败','data'=>$exception->getMessage()]);
                }

            }
            return $this->asJson(['code'=>1,'msg'=>'未检测到文件内容']);
        } else {
            return $this->asJson(['code'=>0, 'msg'=>'导入失败：文件保存失败', 'data'=>$file->error]);
        }

        return $this->asJson(['code'=>1,'data'=>$file->extension]);

    }

}